package com.gtlab1207.br_security.common;


import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 *
 */
public class HttpConfig {



    public static String doPostXml(String url,String params){
        CloseableHttpResponse closeableHttpResponse = doPost(url,params);
        return readResponse(closeableHttpResponse);
    }

    /**
     * post请求
     *
     * @param uri
     * @param params
     * @return
     */
    public static CloseableHttpResponse doPost(String uri, String params) {
        try {

            CloseableHttpClient client = HttpClients.createDefault();

            HttpPost http = new HttpPost(uri);
            http.setHeader("Content-Type", "application/json;charset=utf-8");
            StringEntity postingString = new StringEntity(params,"utf-8");
            http.setEntity(postingString);
            CloseableHttpResponse response = client.execute(http);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * get请求
     *
     * @param uri
     * @param client
     * @param response
     * @return
     */
    public static CloseableHttpResponse doGet(String uri, HttpServletResponse response, CloseableHttpClient client) {
        try {
            HttpGet get = new HttpGet(uri);    //创建get请求
            get.setHeader("Content-Type", "application/x-www-form-urlencoded");
            CloseableHttpResponse httpResponse = client.execute(get);   //执行get请求
            //只能被消费一次
            HttpEntity entity = httpResponse.getEntity();
            //设置返回的contentType
            response.setContentType(entity.getContentType().getValue());
            return httpResponse;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * 读取  CloseableHttpResponse，返回其中结果
     * @param response
     * @return
     */
    public static String readResponse(CloseableHttpResponse response){
        try{
            //返回结果
            if(response != null){
                HttpEntity entity = response.getEntity();
                //仅能被流读取一次
                String message = EntityUtils.toString(entity, "utf-8");
                EntityUtils.consume(entity);
                //关闭httpclient
                response.close();
                response.close();
                return message;
            }else
                return null;
        }catch (Exception ex){
            ex.printStackTrace();
            return null;
        }

    }

    /**
     * put请求
     *
     * @param uri
     * @param httpEntity
     * @param request
     * @param client       httpClient
     * @return
     */
    public static CloseableHttpResponse doPut(String uri, HttpEntity httpEntity, HttpServletRequest request, CloseableHttpClient client) {
        try {
            HttpPut http = new HttpPut(uri);
            http.setHeader("Content-Type", "application/x-www-form-urlencoded");
            http.setEntity(httpEntity);
            CloseableHttpResponse response = client.execute(http);
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static JSONObject get(String url) {
        CloseableHttpResponse response = null;
        CloseableHttpClient client = HttpClients.createDefault();
        BufferedReader in = null;
        String result = "";
        JSONObject object=null;
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpGet.setConfig(requestConfig);
            httpGet.setConfig(requestConfig);
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            response = client.execute(httpGet);
            in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer("");
            String line = "";
            String NL = System.getProperty("line.separator");
            while ((line = in.readLine()) != null) {
                sb.append(line + NL);
            }
            in.close();
            result = sb.toString();
            object= JSONObject.fromObject(result);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != response) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return object;
    }

}
